/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package simplepushserver.gui;

import java.util.ArrayList;
import java.util.List;
import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

/**
 * @author Filip
 */
public class ListSyncer<T> implements ListModel{
    private List<T> list;
    private ArrayList<ListDataListener> listners;

    public ListSyncer(List list) {
        this.list = list;
        this.listners = new ArrayList<ListDataListener>();
        triggerListeners();
    }

    public void addAll(List<T> newList){
        for (T t : newList) {
            list.add(t);
        }
        triggerListeners();
    }

    public void addElement(T t){
        list.add(t);
        triggerListeners();
    }
    public void insertElement(T t, int index){
        list.add(index, t);
        triggerListeners();
    }
    public void removeElement(T t){
        list.remove(t);
        triggerListeners();
    }
    public T removeElementAt(int index){
        T t = list.remove(index);
        triggerListeners();
        return t;
    }
    public void clear(){
        list.clear();
        triggerListeners();
    }

    public int getSize() {
        return list.size();
    }

    public Object getElementAt(int index) {
        return list.get(index);
    }

    public void moveElementUp(int index){
        if(index>0 && index<list.size()){
            T t = removeElementAt(index);
            insertElement(t, index-1);
            triggerListeners();
        }
    }
    public void moveElementDown(int index){
        if(index>=0 && index<list.size()-1){
            T t = removeElementAt(index);
            insertElement(t, index+1);
        }
    }

    private void triggerListeners(){
        for(ListDataListener ldl : listners){
            ldl.contentsChanged(new ListDataEvent(list, ListDataEvent.CONTENTS_CHANGED, 0, list.size()-1));
        }
    }
    public void update(){
        triggerListeners();
    }

    public void addListDataListener(ListDataListener l) {
        listners.add(l);
    }

    public void removeListDataListener(ListDataListener l) {
        listners.remove(l);
    }

    public List<T> getList() {
        return list;
    }
}

